package com.lw.leetcode.stack.b;

import java.util.Arrays;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * 735. 行星碰撞
 * 剑指 Offer II 037. 小行星碰撞
 *
 * @author liw
 * @version 1.0
 * @date 2021/11/9 8:58
 */
public class AsteroidCollision {

    public static void main(String[] args) {
        AsteroidCollision test = new AsteroidCollision();

        // [10]
        int[] arr = {10, 2, -5};

        // [-2,-1,1,2]
//        int[] arr =  {-2,-1,1,2};

        int[] ints = test.asteroidCollision(arr);

        System.out.println(Arrays.toString(ints));
    }

    public int[] asteroidCollision(int[] asteroids) {
        Stack<Integer> stack = new Stack<>();
        for (int a : asteroids) {
            while (true) {
                if (stack.isEmpty()) {
                    stack.add(a);
                    break;
                }
                int peek = stack.peek();
                if ((peek > 0 && a > 0) || (peek < 0 && a < 0) || (peek < 0 && a > 0)) {
                    stack.add(a);
                    break;
                }
                if (peek + a == 0) {
                    stack.pop();
                    break;
                }
                if (peek + a > 0) {
                    break;
                }
                stack.pop();
            }
        }
        int[] arr = new int[stack.size()];
        int index = stack.size() - 1;
        while (!stack.isEmpty()) {
            arr[index--] = stack.pop();
        }
        return arr;
    }

}
